<!--
 * @Author: lihaogn
 * @Date: 2021-12-05 21:16:01
 * @LastEditTime: 2022-05-27 17:55:51
 * @LastEditor: lihaogn
 * @Description: 新增管理员对话框
 * @FilePath: \lix-admin-client-vue2\src\views\system\user-manage\user-list\modules\NewOrUpdateUserDialog.vue
-->
<template>
  <!-- 新增管理员对话框 start -->
  <el-dialog
    :close-on-click-modal="false"
    :title="(type === 'NEW' ? '新增' : '修改') + '用户'"
    :visible.sync="dialogVisible"
    width="420px"
    v-loading="loading"
    @close="handleDialogCancel('adminForm')"
  >
    <el-form
      ref="adminForm"
      :model="adminForm"
      :rules="adminFormRules"
      size="small"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          type="text"
          v-model.trim="adminForm.username"
          autocomplete="off"
          :autofocus="true"
          :show-word-limit="true"
          :maxlength="20"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="真实姓名" prop="realname">
        <el-input
          type="text"
          v-model.trim="adminForm.realname"
          autocomplete="off"
          :show-word-limit="true"
          :maxlength="20"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item v-if="type === 'NEW'" label="密码" prop="password">
        <el-input
          type="password"
          v-model.trim="adminForm.password"
          autocomplete="new-password"
          :maxlength="20"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="type === 'NEW'" label="确认密码" prop="rePassword">
        <el-input
          type="password"
          v-model.trim="adminForm.rePassword"
          autocomplete="new-password"
          :maxlength="20"
        ></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select
          v-model="adminForm.role"
          multiple
          collapse-tags
          placeholder="请选择"
        >
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          type="text"
          v-model.trim="adminForm.mobile"
          autocomplete="off"
          :maxlength="11"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          type="text"
          v-model.trim="adminForm.email"
          autocomplete="off"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="是否启用">
        <el-switch
          v-model="adminForm.status"
          active-color="#13ce66"
          :active-value="UserStatus.ON"
          :inactive-value="UserStatus.OFF"
        >
        </el-switch>
        <span style="margin-left:10px;">{{
          adminForm.status === UserStatus.ON ? '已启用' : '未启用'
        }}</span>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button
        type="primary"
        @click="handleDialogOk('adminForm')"
        :loading="okButtonLoading"
        >确 定</el-button
      >
    </span>
  </el-dialog>
  <!-- 新增管理员对话框 end -->
</template>

<script>
import { reqGetRoleList } from '../../../../../api/user-manage/role/api'
// 请求接口方法
import {
  reqQueryOneUser,
  reqNewUser,
  reqEditUser
} from '../../../../../api/user-manage/user/api'
import { dialogMixin } from '../../../../../mixins/dialog'
import { USER_STATUS } from '../../../../../constant/index'
export default {
  mixins: [dialogMixin],

  data() {
    // 定义新增用户时用户名校验规则，检查用户名是否已经存在
    let validateNewname = async (rule, value, callback) => {
      if (value) {
        if (this.type === 'EDIT') {
          if (value === this.oldName) {
            callback()
          }
        } else {
          // 发起请求，查询用户名是否已经存在
          const res = await reqQueryOneUser({ name: value })
          if (res.result.isExists) {
            callback(new Error(res.message))
          } else {
            callback()
          }
        }
      } else {
        callback()
      }
    }
    // 定义修改密码校验规则
    let validatePass = (rule, value, callback) => {
      // 验证密码规则
      if (value === this.adminForm.oldPassword) {
        callback(new Error('新密码与原密码相同，请重新输入！'))
      }
      if (this.adminForm.checkPassword !== '') {
        // 验证确认密码
        this.$refs.adminForm.validateField('checkPassword')
      }
      callback()
    }
    // 定义修改时确认密码校验规则
    let validateCheckPass = (rule, value, callback) => {
      if (value !== this.adminForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 定义手机号的校验规则
    let validateCheckMobile = (rule, value, callback) => {
      if (value) {
        let reg = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确格式的手机号码'))
        }
      }
      callback()
    }
    // 定义邮箱的校验规则
    let validateCheckEmail = (rule, value, callback) => {
      if (value) {
        let reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确格式的邮箱'))
        }
      }
      callback()
    }
    return {
      adminForm: {
        username: '',
        realname: '',
        password: '',
        rePassword: '',
        role: [],
        mobile: '',
        email: '',
        status: USER_STATUS.ON
      },
      adminFormRules: {
        username: [
          { validator: validateNewname, trigger: 'blur' },
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在3-20个字符', trigger: 'blur' }
        ],
        realname: [
          { min: 2, max: 20, message: '长度在2-20个字符', trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' },
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在3-20个字符', trigger: 'blur' }
        ],
        rePassword: [
          { validator: validateCheckPass, trigger: 'blur' },
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在3-20个字符', trigger: 'blur' }
        ],
        role: [{ required: true, message: '请选择角色', trigger: 'change' }],
        mobile: [{ validator: validateCheckMobile, trigger: 'blur' }],
        email: [
          { validator: validateCheckEmail, trigger: 'blur' },
          { max: 50, message: '长度在50个字符内', trigger: 'blur' }
        ]
      },
      // 用户状态枚举对象
      UserStatus: USER_STATUS,
      roleOptions: [
        {
          id: 1,
          name: '超级管理员'
        },
        {
          id: 2,
          name: '管理员'
        }
      ],
      oldName: ''
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.dialogVisible = val
        this.loading = true
        this.getRoles()

        if (this.type === 'EDIT') {
          // 修改模式
          // 1 回填信息
          this.oldName = this.dialogData.name
          this.adminForm = {
            username: this.oldName,
            realname: this.dialogData.realname,
            role: this.dialogData.role.length
              ? this.dialogData.role.map(x => {
                  return x.id
                })
              : [],
            mobile: this.dialogData.mobile,
            email: this.dialogData.email,
            status: this.dialogData.status
          }
        }
        this.loading = false
      } else {
        this.adminForm = {
          username: '',
          realname: '',
          password: '',
          rePassword: '',
          role: [],
          mobile: '',
          email: '',
          status: USER_STATUS.ON
        }
      }
    }
  },

  methods: {
    /**
     * @author: lihaogn
     * @Date: 2021-12-19 16:16:14
     * @description: 获取所有可选角色
     * @param {*}
     * @return {*}
     */
    async getRoles() {
      const res = await reqGetRoleList()
      if (res.success) {
        this.roleOptions = res.result
      } else {
        this.roleOptions = []
      }
    },
    /**
     * @description: 取消事件
     * @param {*} formName
     * @return {*}
     */
    handleDialogCancel(formName) {
      this.$emit('update:visible', false)
      this.adminForm.status = USER_STATUS.ON
      this.$refs[formName].resetFields()
    },
    /**
     * @description: 确认事件
     * @param {*} formName
     * @return {*}
     */
    handleDialogOk(formName) {
      this.okButtonLoading = true

      this.$refs[formName].validate(async valid => {
        if (valid) {
          let res
          if (this.type === 'NEW') {
            // 新增
            let password = this.$md5(this.adminForm.password)
            res = await reqNewUser(
              Object.assign({}, this.adminForm, { password })
            )
          } else {
            // 修改
            res = await reqEditUser(this.dialogData.id, {
              ...this.adminForm,
              type: 'EDIT'
            })
          }

          if (res.success) {
            this.$message.success(res.message)
            this.dialogVisible = false
            this.$emit('ok')
          }
          this.okButtonLoading = false
        } else {
          this.okButtonLoading = false
          return false
        }
      })
    }
  }
}
</script>

<style></style>
